import { _pick, isUndefined, isArray, isInteger } from "mmb";
import { AppCTX } from "../../types/koaExtend";
import { createStoreApiMWRouter } from "../../middleware/store-api/storeOwnerChecker";
import {
  listSearchObjectsAsStore
} from "../../service/commonService"
import {
  getStoreWithStatAndAccount,
  updateStoreInfo,
  createStoreAccountWithdrawApplyment,
  listStoreAccountWithdrawApplyments,
  listStoreAccountLogs,
  aggrStoreAccountLogsToInOut,
  listStoreProductGroups,
  listStoreProductWithDistributeInfos,
  listStoreProductWithDistributeInfosByProductIDs,
  upsertStoreEndorsement,
  getStoreEndorsementByStoreIDSafely,
} from "../../service/storeService";
import pageMW from "../../middleware/pager";
import { isWithdrawTarget } from "../../bg-enums/withdrawTarget";
import UserStratification, {
  isUserStratification,
} from "../../bg-enums/userStratification";
import { isSearchTerm } from "../../bg-enums/searchTerm";
import { everyIsStoreEndorseApplyField } from "../../bg-enums/storeEndorseApplyField";
const router = createStoreApiMWRouter();

//获取门店信息
router.get("/sto/:storeId/store", async (ctx: AppCTX, next) => {
  // const { userId } = ctx;
  const { storeId } = ctx.params;
  const { page } = ctx.query;
  const storeWithStatAndAccount = await getStoreWithStatAndAccount(storeId);
  ctx.body = {
    ...storeWithStatAndAccount,
  };
});

// 更新门店信息
router.put("/sto/:storeId/store/update", async (ctx: AppCTX, next) => {
  // const { userId } = ctx;
  const { storeId } = ctx.params;
  const { name, intro, pic, homepageBg, tel } = ctx.request.body;
  const store = await updateStoreInfo({
    storeId,
    name,
    intro,
    pic,
    homepageBg,
    tel,
  });

  ctx.body = {
    ...store,
  };
});

// 获取门店的代言信息
router.get("/sto/:storeId/store/endorsement", async (ctx: AppCTX, next) => {
  const { userId } = ctx;
  const { storeId } = ctx.params;

  const storeEndorsement = await getStoreEndorsementByStoreIDSafely(storeId);
  ctx.body = {
    ...storeEndorsement,
  };
});

// 设置门店的代言信息
router.put("/sto/:storeId/store/endorsement", async (ctx: AppCTX, next) => {
  const { userId } = ctx;
  const { storeId } = ctx.params;
  const {
    isOpen,
    spokesmanTitle,
    userStratified,
    needApplyInfo,
    isEntranceDisplay,
    isAutoApproved,
  } = ctx.request.body;
  let { consumerLowerExpense, applyInfoFields } = ctx.request.body;

  // chdck field releation
  if (!isUserStratification(userStratified)) {
    ctx.throw("400", "userStratified is invalid");
  } else {
    if (userStratified === UserStratification.ANYONE) {
      consumerLowerExpense = undefined;
    } else {
      if (!isInteger(consumerLowerExpense)) {
        ctx.throw("400", "consumerLowerExpense is invalid");
      }
    }
  }

  if (needApplyInfo) {
    if (!everyIsStoreEndorseApplyField(applyInfoFields)) {
      ctx.throw("400", "applyInfoFields is invalid");
    }
  } else {
    applyInfoFields = undefined;
  }

  const storeEndorsement = await upsertStoreEndorsement({
    storeId,
    isOpen,
    spokesmanTitle,
    userStratified,
    consumerLowerExpense,
    needApplyInfo,
    applyInfoFields,
    isEntranceDisplay,
    isAutoApproved,
  });

  ctx.body = {
    ...storeEndorsement,
  };
});

// 门店申请提现
router.post(
  "/sto/:storeId/store/accountWithdrawApplyment",
  async (ctx: AppCTX, next) => {
    const { userId } = ctx;
    const { storeId } = ctx.params;
    const { target, amount, realName, idCardNo, remark } = ctx.request.body;

    if (!isWithdrawTarget(target)) {
      ctx.throw(400, "invalid target");
    }

    const storeAmountWithdrawApplyment =
      await createStoreAccountWithdrawApplyment({
        storeId,
        target,
        amount,
        realName,
        idCardNo,
        remark,
      });

    ctx.body = storeAmountWithdrawApplyment;
  }
);

// 获取门店的提现记录列表
router.get(
  "/sto/:storeId/store/accountWithdrawApplyments",
  pageMW,
  async (ctx: AppCTX, next) => {
    const { userId, limit, offset } = ctx;
    const { storeId } = ctx.params;
    const { total, items } = await listStoreAccountWithdrawApplyments(storeId, {
      limit,
      offset,
    });
    ctx.body = {
      total,
      rows: items,
    };
  }
);

// 获取门店的资金明细列表
router.get(
  "/sto/:storeId/store/accountLogs",
  pageMW,
  async (ctx: AppCTX, next) => {
    const { userId, limit, offset, ts } = ctx;
    const { storeId } = ctx.params;
    const { begin, end } = ctx.request.query;

    const { total, items } = await listStoreAccountLogs(
      storeId,
      {
        begin: isUndefined(begin) ? 0 : parseInt(begin),
        end: isUndefined(end) ? Date.now() : parseInt(end),
      },
      {
        limit,
        offset,
        ts,
      }
    );
    ctx.body = {
      total,
      rows: items,
    };
  }
);

// 统计门店的资金收入与支出
router.get(
  "/sto/:storeId/store/aggrAccountLogsToInOut",
  async (ctx: AppCTX, next) => {
    const { userId } = ctx;
    const { storeId } = ctx.params;
    const { begin, end } = ctx.request.query;

    const aggrRet = await aggrStoreAccountLogsToInOut(storeId, {
      begin: isUndefined(begin) ? 0 : parseInt(begin),
      end: isUndefined(end) ? Date.now() : parseInt(end),
    });

    ctx.body = aggrRet;
  }
);

// 列出门店商品分组
router.get("/sto/:storeId/productGroups", pageMW, async (ctx: AppCTX, next) => {
  const { userId, limit, offset, ts } = ctx;
  const { storeId } = ctx.params;

  const { total, items } = await listStoreProductGroups(userId, storeId, {
    limit,
    offset,
    ts,
  });

  ctx.body = {
    total,
    rows: items,
  };
});

// 列出门店商品
router.get("/sto/:storeId/products", pageMW, async (ctx: AppCTX, next) => {
  const { userId, limit, offset, ts } = ctx;
  const { storeId } = ctx.params;
  let { productGroupId, keyword } = ctx.query;

  const { total, items } = await listStoreProductWithDistributeInfos(
    { userId, storeId, productGroupId, keyword },
    {
      limit,
      offset,
      ts,
    }
  );

  ctx.body = {
    total,
    rows: items,
  };
});

// 根据商品id列出门店商品
router.post(
  "/sto/:storeId/productsByIds",
  pageMW,
  async (ctx: AppCTX, next) => {
    const { userId, limit, offset, ts } = ctx;
    const { storeId } = ctx.params;
    let { productIds } = ctx.request.body;

    if (!isArray(productIds) || productIds.length > 20) {
      ctx.throw(400, "invalid productIds");
    }

    const rows = await listStoreProductWithDistributeInfosByProductIDs(
      { userId, storeId, productIds },
      {
        limit,
        offset,
        ts,
      }
    );

    ctx.body = {
      rows,
    };
  }
);

// 获取门店使用的查询对象列表
router.get(
  "/sto/:storeId/store/searchObjects",
  pageMW,
  async (ctx: AppCTX, next) => {
    const { storeId } = ctx.params;
    const { term, keyword } = ctx.query;
    const { userId, limit, offset } = ctx;

    if (!isSearchTerm(term)) {
      ctx.throw(400, "term invalid");
    }

    const { total, items } = await listSearchObjectsAsStore(
      storeId,
      term,
      keyword,
      {
        limit,
        offset,
      }
    );
    ctx.body = {
      total,
      rows: items,
    };
  }
);

export default router;
